from datetime import datetime

from flask import Flask, jsonify, request
import sys
import os
import json
import pymysql
from shared.dp_config import DB_CONFIG
from flask_cors import CORS
from read_search_file import load_valid_cookie
from open_jg_page_get_cookie import collect_relative_pack_details_id, collect_relative_pack_list_exists, crawl_save_target_package, get_indus_category_tree, collect_recom_spu_list_exists


file_name = os.path.join("static", "get_jg_data.json")
connection = pymysql.Connect(**DB_CONFIG)

app = Flask(__name__)
CORS(app)  # 启用CORS

def get_resource_path(relative_path):
    """ 获取资源绝对路径 """
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


@app.route('/api/save_target_configs_spu_map', methods=['POST'])
def save_target_configs_spu_map():
    data = request.get_json()

    outTargetConfigs = data.get('outTargetConfigs')
    taxonomyCode = data.get('taxonomyCode')
    taxonomyName = data.get('taxonomyName')
    recomSpu = data.get('recomSpu')

    if not isinstance(outTargetConfigs, list):
        return jsonify({"error": "outTargetConfigs 必须是数组"}), 400

    try:
        with connection.cursor() as cursor:
            sql = """
                INSERT INTO auto_plan_capture_target_config_data 
                (target_config_data, create_time, taxonomy_code, taxonomy_name, recom_spu, target_config_data_id)
                VALUES (%s, %s, %s, %s, %s, %s)
            """
            current_time = datetime.now().strftime("%Y.%m.%d %H:%M:%S")
            for target_config in outTargetConfigs:
                target_config_data_id = target_config['id']
                cursor.execute(sql, (
                    json.dumps(target_config, ensure_ascii=False),  # 每个数组元素存入 target_config_data 字段
                    current_time,
                    taxonomyCode,
                    taxonomyName,
                    recomSpu,
                    target_config_data_id
                ))
        connection.commit()
        return jsonify({"status": "success", "taxonomyCode": taxonomyCode})

    except Exception as e:
        connection.rollback()
        print(f"写入数据库失败: {e}")
        return jsonify({"error": "写入缓存失败"}), 500



@app.route('/api/get_indus_category_tree', methods=['GET'])
def get_indus_category_tree_data():
    try:
        taxonomy_code = request.args.get('taxonomy_code')

        json_path = get_resource_path(file_name)
        cookie, account_id = load_valid_cookie(file_name=json_path)

        taxonomy_name = get_indus_category_tree(cookies=cookie, account_id=account_id, taxonomy_code=taxonomy_code)

        return jsonify({"status": "success", "taxonomy_name": taxonomy_name})

    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 400

@app.route('/api/copy_target_package', methods=['POST'])
def copy_target_package():
    try:
        json_path = get_resource_path(file_name)

        data = request.get_json()
        target_config = data.get('target_config')

        cookie, account_id = load_valid_cookie(file_name=json_path)
        res_json = crawl_save_target_package(cookies=cookie, account_id=account_id, data=target_config)

        if res_json and res_json.get('code') == 0:
            return jsonify({'success': True, 'message': res_json}), 200
        else:
            return jsonify({'fail': False, 'message': res_json}), 400

    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 400

@app.route('/api/temp_target_packages_details_byid', methods=['GET'])
def temp_target_packages_details_byid():
    # 获取 GET 请求中的参数
    try:
        pkg_id = request.args.get('pkg_id')
        connection = pymysql.Connect(**DB_CONFIG)
        print("数据库连接成功!")

        with connection.cursor() as cursor:
            sql = """
                SELECT id, target_config_data, create_time
                FROM auto_plan_capture_target_config_data
                WHERE id = %s
            """
            cursor.execute(sql, (pkg_id,))
            result = cursor.fetchone()

        if result:
            config_data = json.loads(result[1])
            return jsonify({"status": "success", "target_config": config_data})
        else:
            return jsonify({"error": "未找到对应的数据"}), 404

    except Exception as e:
        print(f"查询数据失败: {e}")
        return jsonify({"error": "获取配置数据失败"}), 500
@app.route('/api/get_monitor_target_config_detail', methods=['GET'])
def get_monitor_target_config_detail():
    try:
        with connection.cursor() as cursor:
            taxonomy_code = request.args.get('taxonomy_code')

            sql = """
                SELECT id, target_config_data, create_time
                FROM auto_plan_capture_target_config_data
            """

            if taxonomy_code:
                sql += " WHERE taxonomy_code = %s ORDER BY create_time DESC"
                cursor.execute(sql, (taxonomy_code,))
            else:
                sql += " ORDER BY create_time DESC"
                cursor.execute(sql)

            results = cursor.fetchall()

        # 转换为列表字典格式返回
        all_target_config = [{"id": row[0], "target_config_temp_name": json.loads(row[1])['name']} for row in results]
        return jsonify({"status": "success", "all_target_config_temp": all_target_config})

    except Exception as e:
        print(f"查询数据失败: {e}")
        return jsonify({"error": "获取定向包数据失败"}), 500

# 收集浏览器插件监测到的定向包数据提交到测试数据库 - 后续作为模板包
@app.route('/api/monitor_target_config', methods=['POST'])
def monitor_target_config():
    data = request.get_json()
    target_config_data = data.get('target_config_data')

    if not target_config_data:
        return jsonify({"error": "没有监测到body数据"}), 400

    connection = pymysql.Connect(**DB_CONFIG)
    print("数据库连接成功!")

    try:
        with connection.cursor() as cursor:
            sql = """
                INSERT INTO auto_plan_capture_target_config_data (target_config_data, create_time)
                VALUES (%s, %s)
            """
            cursor.execute(sql, (
                target_config_data,
                datetime.now().strftime("%Y.%m.%d %H:%M:%S"),
            ))
        connection.commit()
        return jsonify({"status": "success", "target_config_data": target_config_data})

    except Exception as e:
        print(f"写入JSON失败: {e}")
        return jsonify({"error": "关联定向包表单数据写入失败"}), 500

@app.route('/api/target_packages_details', methods=['GET'])
def target_packages_details():
    # 获取 GET 请求中的参数
    json_path = get_resource_path(file_name)
    pkg_id = request.args.get('pkg_id')
    try:
        cookie, account_id = load_valid_cookie(file_name=json_path)
        targetConfig = collect_relative_pack_details_id(cookies=cookie, account_id=account_id, pkg_id=pkg_id)

        return jsonify({
            'outTargetConfig': targetConfig
        })
    except Exception as e:
        return jsonify({
            'targetConfig': {}
        }), 500

@app.route('/api/target_packages_all')
def target_packages_all():
    try:
        json_path = get_resource_path(file_name)
        cookie, account_id = load_valid_cookie(file_name=json_path)
        targetPackages = collect_relative_pack_list_exists(cookies=cookie, account_id=account_id)
        return jsonify({'targetPackages': targetPackages})
    except Exception as e:
        print(f"Error loading packages: {e}")
        return jsonify({'targetPackages': ["默认人群包"]})

@app.route('/api/target_packages')
def get_target_packages():
    try:
        json_path = get_resource_path(file_name)
        cookie, account_id = load_valid_cookie(file_name=json_path)
        spu_name_code_list = collect_recom_spu_list_exists(cookies=cookie, account_id=account_id)

        json_path = get_resource_path(file_name)
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        return jsonify({
            'account_id': data.get('account_id', ''),
            'spu_name_list': spu_name_code_list
        })
    except Exception as e:
        print(f"Error loading packages: {e}")
        return jsonify({"error": "获取基础数据信息失败"}), 500


@app.route('/api/upload_file', methods=['POST'])
def upload_file():
    data = request.get_json()
    file_path = data.get('filePath')

    if not file_path:
        return jsonify({"error": "缺少文件路径"}), 400

    try:
        json_path = get_resource_path(file_name)
        # 读取现有数据
        if os.path.exists(json_path):
            with open(json_path, 'r', encoding='utf-8') as f:
                current_data = json.load(f)
        else:
            current_data = {}

        # 更新文件路径
        current_data['selected_file'] = file_path

        # 写回文件
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(current_data, f, ensure_ascii=False, indent=2)

        return jsonify({"status": "success", "filePath": file_path})

    except Exception as e:
        print(f"写入JSON失败: {e}")
        return jsonify({"error": "写入缓存失败"}), 500

def start_server():
    app.run(port=5000)